﻿using System;
using Game.Common;
using Game.ExtensibleObjects;
using Game.Objects;
using System.Windows;

namespace Game.Map.Extensions
{
    public static class MoveExtensionHelper
    {
        public static MapMoveExtension MoveX(this IGameMap map)
        {
            return map.Extensions.Find<MapMoveExtension>();
        }
    }

    public class MapMoveExtension : IRuntimeExtension
    {
        public event EventHandler<MoveEventArgs> Move;
        public event EventHandler<MovingItemPositionChangedEventArgs> MovingItemPositionChanged;

        Vehicle _MovingItem;

        public Vehicle MovingItem
        {
            get { return _MovingItem; }
        }

        public void MoveTo(
            IActionCallback callback,
            GamePath path,
            Vehicle item,
            GameTurn turn)
        {
            DoMove(callback, path, item, turn);
        }

        public void SetMovingItem(Vehicle item, double x, double y)
        {
            _MovingItem = item;

            var args = new MovingItemPositionChangedEventArgs(new Point(x, y));
            if (MovingItemPositionChanged != null)
            {
                MovingItemPositionChanged(this, args);
            }
        }

        void DoMove(IActionCallback callback,
                    GamePath path,
                    Vehicle item,
                    GameTurn turn)
        {
            if (Move != null)
            {
                var args = new MoveEventArgs(callback, path, item, turn);
                Move(this, args);

                GameDebug.Assert(args.IsHandled);
            }
        }
    }

    public class MapMoveExtensionFactory : IRuntimeExtensionFactory
    {
        public IRuntimeExtension CreateExtension(IRuntimeExtensibleObject source)
        {
            return new MapMoveExtension();
        }
    }

    public class MovingItemPositionChangedEventArgs : EventArgs
    {
        readonly Point _point;

        public MovingItemPositionChangedEventArgs(Point point)
        {
            _point = point;
        }

        public Point Point
        {
            get { return _point; }
        }
    }

}
